import { store } from "@/store"
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { showError } from '@/utils/msg-show'
import { getPageApi } from '@/api/sys/organization'

export const useOrganizationStore = defineStore("Organization", () => {
	const isZero = ref(true)
	const dataList = ref<any[]>([])
	const query = reactive<any>({
		pageNum: 1,
		pageSize: 10,
		totalSize: 0,
	})

    /** 获取所有组织结构/代理商 */
    async function getPage(){
       await search(query)
    }

      
	async function search(params: any){
		 await getPageApi(params).then((res: any) => {
			query.totalSize = res.data.total
			if(query.pageNum == 1){
				dataList.value = res.data.list
			}else{
				dataList.value = dataList.value.concat(res.data.list)
			}
		}).catch(err => {
			showError(err.msg || err.errMsg || err)
		})
	}

	/** 初始化 */
	async function init() {
		if (isZero.value) {
            await getPage()
			isZero.value = false
		}
	}

    function update(){
		 const size = query.pageNum * query.pageSize
         search({...query, pageNum: 1, pageSize: size })
	}

	return {
		init, update, getPage,
        dataList, query
	}

})

export function useOrganizationStoreHook() {
	return useOrganizationStore(store);
}